package com.hippo.core.util;

import com.google.gson.Gson;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.Objects;
import java.util.UUID;

/**
 * 七牛云文件上传工具类
 *
 * @author hippo
 */
@Component
public class QiniuUtils {

    @Value("${qiniu.accessKey}")
    private String accessKey;      //公钥
    @Value("${qiniu.secretKey}")
    private String accessSecretKey;   //私钥
    @Value("${qiniu.bucketName}")
    private String bucketName;   // 存储空间
    @Value("${qiniu.path}")
    private String path;       // 域名

    /**
     * @param file 前端传来的图片
     * @return 图片的访问路径
     */
    public String upload(MultipartFile file) {
        // 生成文件名
        String fileName = getRandomImgName(Objects.requireNonNull(file.getOriginalFilename()));
        //构造一个带指定 Region 对象的配置类
        Configuration cfg = new Configuration(Region.autoRegion());  //根据自己的对象空间的地址选（华东）
        //...其他参数参考类注释
        UploadManager uploadManager = new UploadManager(cfg);
        //默认不指定key的情况下，以文件内容的hash值作为文件名
        try {
            byte[] uploadBytes = file.getBytes();
            Auth auth = Auth.create(accessKey, accessSecretKey);
            String upToken = auth.uploadToken(bucketName);
            Response response = uploadManager.put(uploadBytes, fileName, upToken);
            //解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            return path + fileName;
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return null;
    }

    /**
     * @Param: fileName
     * @return: 云服务器fileName
     */
    public static String getRandomImgName(String fileName) {
        int index = fileName.lastIndexOf(".");
        if (fileName.isEmpty() || index == -1) {
            throw new IllegalArgumentException();
        }
        // 获取文件后缀
        String suffix = fileName.substring(index).toLowerCase();
        // 生成UUID
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        // 拼接新的名称
        return uuid + suffix;
    }

    /**
     * 根据操作系统构建当前存放路径
     *
     * @return 文件路径
     */
    public static String getFileUrl() {
        String fileUrl = "";
        if (SystemUtil.isWindows()) {
            fileUrl = "file:\\" + System.getProperty("user.dir") + "\\build\\reports\\tests\\";
        } else {
            fileUrl = "file:" + System.getProperty("user.dir") + "/build/reports/tests/";
        }
        return fileUrl;
    }

    public String getImagePath(QiniuUtils qiniuUtils ,String filePath) {
        try {
            File file = UrlToFIle.getFile(filePath);
            MultipartFile multipartFile = new MockMultipartFile("file", file.getName(), null, new FileInputStream(file));
            String imagePath = qiniuUtils.upload(multipartFile);
            return imagePath;
        } catch (Exception e) {
            e.printStackTrace();
            return e.toString();
        }
    }

    public static void main(String[] args) {
        File file = UrlToFIle.getFile(getFileUrl() + "输入java-1665128084495.png");
        try {
            MultipartFile multipartFile = new MockMultipartFile("file", file.getName(), null, new FileInputStream(file));
            QiniuUtils qiniuUtils = new QiniuUtils();
            String imagePath = qiniuUtils.upload(multipartFile);
            System.out.println(imagePath);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}